from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
import time
from com.kjssoft.common.globals import EagleyeAssist
from com.kjssoft.eagleye.models import EEUser
from com.kjssoft.rainbow import LOGGER
from com.kjssoft.rainbow.album.forms import RainbowPhotoFrameAlbumForm
from com.kjssoft.rainbow.album.models import RainbowPhotoFrameAlbum
from com.kjssoft.rainbow.album.services import UserAlbumProfile
from com.kjssoft.rainbow.views import response_format_decorator

__author__ = 'Sea'

def model_instance_decorator(view_func):
    def _wrapper_view_func(request, album_instance = None, user_instance = None, *args, **kwargs):
        LOGGER.debug(album_instance)
        LOGGER.debug(user_instance)
        try:
            user_instance = EEUser.objects.get(id = user_instance)
            album_instance = RainbowPhotoFrameAlbum.objects.get(
                id = album_instance,
                user = user_instance
            )
            user_album_profile = UserAlbumProfile(request.user, album_instance)
            album_instance.profile = user_album_profile
            return view_func(request, album_instance, user_instance, *args, **kwargs)
        except RainbowPhotoFrameAlbum.DoesNotExist as e:
            LOGGER.error(e)
        except EEUser.DoesNotExist as e:
            LOGGER.error(e)
        return redirect('/rainbow/showcase')
    return _wrapper_view_func

@response_format_decorator
def list_view_page(request, user_instance = None):
    LOGGER.debug('request to list albums of user %s, who is logged ? %s' % (request.user, request.user.is_authenticated()))
    try:
        user_instance = EEUser.objects.get(id = user_instance)
        user_album_profile = UserAlbumProfile(user_instance)
        albums = user_album_profile.albums
        LOGGER.debug('albums %s of user %s' % (albums, user_instance))
        if 'list' == request.response_format:
            return render_to_response(
                'kjs/rainbow/album/list_list.html',
                {
                    'album_list':albums,
                    'user_instance':user_instance,
                    },
                context_instance = RequestContext(request)
            )
        return render_to_response(
            'kjs/rainbow/album/list.html',
            {
                'album_list':albums,
                'user_instance':user_instance,
            },
            context_instance = RequestContext(request)
        )
    except EEUser.DoesNotExist as e:
        LOGGER.error(e)
        return redirect('/rainbow/showcase')



@model_instance_decorator
@response_format_decorator
def show_view_page(request, album_instance = None, user_instance = None):
    LOGGER.debug('================================ %s' % album_instance.profile)
    if 'sample' == request.response_format:
        empty = range(0, 9 - len(album_instance.profile.snapshot_photos))
        return render_to_response(
            'kjs/rainbow/album/show_sample.html',
            {
                'album_instance':album_instance,
                'empty':empty
            },
            context_instance = RequestContext(request)
        )
    photo_list = album_instance.profile.album_photos
    count = photo_list.count()
    index = 0
    scope = 20
    if count < index:
        photo_list = []
    else:
        end_index = index + scope
        if count < end_index:
            end_index = count
        photo_list = photo_list[index:end_index]
    return render_to_response(
        'kjs/rainbow/album/show.html',
        {
            'album_instance':album_instance,
            'photo_list':photo_list,
            'count':count,
            'index':index,
            'scope':scope
        },
        context_instance = RequestContext(request)
    )

@transaction.commit_on_success
def add_view_page(request):
    if request.POST:
        form = RainbowPhotoFrameAlbumForm(request.POST)
        if form.is_bound and form.is_valid():
            album_instance = form.instance
            album_instance.user = request.user
            album_instance.create_ms = int(time.time())
            album_instance.status = 1
            album_instance.save()
            return redirect('/rainbow/album/%s/of/user/%s/show' % (album_instance.id, album_instance.user.id))
    form = RainbowPhotoFrameAlbumForm(initial={})
    return render_to_response(
        'kjs/rainbow/album/add.html',
        {
            'form':form
        },
        context_instance = RequestContext(request)
    )

@login_required(login_url = EagleyeAssist.get_login_url())
@transaction.commit_on_success
def edit_view_page(request, album_instance = None):
    album_instance = RainbowPhotoFrameAlbum.objects.get(
        id = album_instance,
        user = request.user
    )
    if request.POST:
        form = RainbowPhotoFrameAlbumForm(request.POST, instance = album_instance)
        if form.is_bound and form.is_valid():
            form.save()
        return redirect('/rainbow/album/%s/of/user/%s/show' % (album_instance.id, album_instance.user.id))
    form = RainbowPhotoFrameAlbumForm(initial={
        'name':album_instance.name
    })
    return render_to_response(
        'kjs/rainbow/album/edit.html',
        {
            'form':form
        },
        context_instance = RequestContext(request)
    )